使用 Swagger 自動生成 API 文件 能大大減少手動編寫 API 文檔的時間和錯誤,這也是很多開發團隊選擇使用它的原因。Swagger 提供多種方式來自動生成 API 文檔,特別是對於後端開發者來說,它能直接從代碼中提取 API 定義並生成符合 OpenAPI 規範的文檔。
Swagger 自動化文檔生成流程
選擇適合的 Swagger 工具:
在代碼中添加注解:
通常,我們可以在 REST API 控制器和方法中添加注解,Swagger 會根據這些注解自動生成 API 文檔。以下是 Java(Spring Boot)使用 Swagger 的一個簡單範例:
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
    @Operation(summary = "Get a user by ID", 
               description = "Returns a user object when the given user ID is valid.",
               responses = {
                  @ApiResponse(responseCode = "200", description = "Successful operation",
                        content = @Content(mediaType = "application/json",
                        schema = @Schema(implementation = User.class))),
                  @ApiResponse(responseCode = "404", description = "User not found")
               })
    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable int id) {
        return new User(id, "John Doe");
    }
}
在這個範例中,我們使用了 @Operation 和 @ApiResponse 等注解來定義 API 文檔。這些注解會被自動掃描並轉換為 OpenAPI 規範的 YAML 或 JSON 文檔。
Swagger 自動化文檔生成的具體步驟(以 Spring Boot + SpringFox 為例)
1. 添加依賴:
在 Spring Boot 項目中引入必要的依賴。編輯 pom.xml,加入 Swagger 和 SpringFox 的依賴:
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
2. 配置 Swagger:
創建一個 Swagger 配置類,這樣可以告訴 SpringFox 自動掃描 REST 控制器。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
                .paths(PathSelectors.any())
                .build();
    }
}
3. 啟動項目: 當啟動 Spring Boot 項目後,Swagger 會自動生成並提供 API 文檔,可以在 /swagger-ui/index.html 路徑上查看。
實踐中的應用範例
訪問 Swagger UI 時,會看到 /users 路徑對應的 GET 操作,點擊後可直接測試 API,並顯示回應格式。
安裝 swagger-jsdoc 和 swagger-ui-express:
npm install swagger-jsdoc swagger-ui-express
在應用中配置 Swagger:
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const express = require('express');
const app = express();
const swaggerOptions = {
    swaggerDefinition: {
        openapi: '3.0.0',
        info: {
            title: 'User API',
            version: '1.0.0',
            description: 'API for managing users'
        }
    },
    apis: ['./routes/*.js'], // 指定包含注解的路徑
};
const swaggerDocs = swaggerJsdoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));
添加 API 注解: 在routes/user.js中:
/**
 * @swagger
 * /users:
 *   get:
 *     summary: Returns a list of users
 *     responses:
 *       200:
 *         description: A JSON array of user names
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: string
 */
app.get('/users', (req, res) => {
    res.json(['John', 'Jane', 'Jack']);
});
啟動應用後,Swagger UI 自動生成可視化文檔,並能通過 /api-docs 路徑查看文檔。
通過使用 Swagger 自動化文檔生成流程,開發者可以輕鬆地在代碼中嵌入 API 定義,並隨時生成最新的 API 文檔。這不僅節省了手動編寫和更新文檔的時間,還能保證 API 文檔與代碼保持同步,非常適合團隊合作和敏捷開發流程。在實踐中,無論是 Java、Node.js 還是其他語言,都有相應的工具和庫可以輕鬆集成 Swagger,提升開發效率。